let state = [],
    stateIndex = 0,
    setters = [];

/**
 * 1. 为什么state全局? why state是数组？
 * a. 防止state更新时导致组件重新执行，进而使得state被重新设置初始值
 * b. 因为useState需要被多次调用
 * 
 * 2. 为什么setters时全局数组？
 * a. 防止rerender重复定义setter方法，消耗内存
 * b. 多次调用
 */
function useState(initialState) {
    // 1. 判断是否已经存在
    state[stateIndex] = state[stateIndex] ? state[stateIndex] : initialState;
    let value = state[stateIndex];
    // 2. set 
    let setterFn = generateSetter(stateIndex);
    stateIndex++;
    return [value, setterFn]
}

const [add, setAdd] = useState(0);

function generateSetter(prop) {
    return function (newVal) {
        let oldVal = state[prop];
        if (oldVal !== newVal) {
            state[prop] = val;
            // rerender
            render();
        }
    }
}

console.log(state, add, setAdd);

// function render() {
//     stateIndex = 0;
//     effectIndex = 0;
//     ReactDOM.render( < App / > , document.getElementById('root'));
// }

const [count, dispatch] = useReducer(reducer, 0);

function reducer(state, action) {
    switch (action.type) {
        case 'increment':
            return state + 1;
        case 'decrement':
            return state - 1;
        default:
            break;
    }
}

function useReducer(reducer, initialState) {
    const [prop, setProp] = useState(initialState);
    function dispatch(action) {
        let newVal = reducer(prop, action);
        setProp(newVal);
    }
    return [state[stateIndex], dispatch];
}